package com.tianci.appstore.ui.search;

import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextUtils.TruncateAt;
import android.text.style.CharacterStyle;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.coocaa.app.gamecenter.pages.detail.DetailActivity;
import com.coocaa.app.gamecenter.pages.search.GameSearchActivity;
import com.coocaa.x.framework.utils.LogUtils;
import com.skyworth.framework.skysdk.ipc.SkyStartActivity;
import com.tianci.appstore.AppDetailActivity;
import com.tianci.appstore.R;
import com.tianci.appstore.SearchActivity;
import com.tianci.appstore.dataprovider.AppDataProvider;
import com.tianci.appstore.ui.SkinManager;
import com.tianci.appstore.ui.data.SkyAppBaseData;
import com.tianci.appstore.ui.data.SkyAppDetailData;
import com.tianci.appstore.ui.data.SkyListAppData;
import com.tianci.appstore.ui.data.SkyListAppData.ListType;
import com.tianci.appstore.ui.list.ListBlock;
import com.tianci.appstore.ui.list.SkyListAdapter.OnItemClickListener;
import com.tianci.appstore.ui.util.UICommon;
import com.tianci.appstore.ui.widget.AlwaysMarqueeTextView;
import com.tianci.appstore.ui.widget.CatchImageView;
import com.tianci.appstore.utils.HLPositionUtil;
import com.tianci.appstore.utils.HLPositionUtil.HLPosition;
import com.tianci.appstore.utils.ImageUtils;
import com.tianci.appstore.utils.SkyConstants;
import com.tianci.appstore.utils.SkyNetImageCache;

import java.util.HashMap;

/**
 * 列表页中的app块View 使用此view的列表有：1.我的应用列表、2.卸载应用列表、3.清理缓存列表、4.应用转移列表
 * 其中1的supportMultiSel为false，而234的为true
 **/
public class SearchListBlock extends ListBlock {
    protected ListType listType;
    protected static int titleSize = SkyConstants.Dpi(35);
    protected static int infoTextSize = SkyConstants.Dpi(25);
    protected ImageView iconImage;
    protected LinearLayout rightLayout;
    protected TextView infoText;
    protected ImageView cornerImage;
    protected Bitmap cornerBitmap;
    protected OnItemClickListener clickListener;
    protected TextView installTagView;
    protected String pkgName;
    protected boolean isSearchHotItem = false;

    public SearchListBlock(Context context, ListType type) {
        super(context, type);
        this.listType = type;
        // TODO Auto-generated constructor stub
        // SkinManager.setBackground(this, R.drawable.search_block_selector);
        this.setPadding(SkyConstants.shadowWidth, SkyConstants.shadowWidth,
                SkyConstants.shadowWidth, SkyConstants.shadowWidth);
        // createView();
    }

    public void addInstallTag() {
        LogUtils.i("addInstallTag");
        if (installTagView == null) {
            installTagView = new TextView(mContext);
            installTagView.setSelected(false);
            installTagView.setClickable(false);
            installTagView.setTextSize(SkyConstants.Dpi(20));
            SkinManager.setTextColor(installTagView, R.color.titleColor);
            LayoutParams layoutParams = new LayoutParams(SkyConstants.Div(89), SkyConstants.Div(43));
            layoutParams.gravity = Gravity.BOTTOM | Gravity.RIGHT;
            installTagView.setGravity(Gravity.CENTER);
            installTagView.setText(mContext.getResources().getString(R.string.installed));
            installTagView.setBackgroundResource(R.drawable.search_installed_bg);
            this.addView(installTagView, layoutParams);
        }

        if (installTagView.getVisibility() != View.VISIBLE)
            installTagView.setVisibility(View.VISIBLE);
    }

    public void removeInstallTag() {
        if (installTagView != null && installTagView.getVisibility() == View.VISIBLE)
            installTagView.setVisibility(View.GONE);

        LogUtils.i("removeInstallTag");
    }

    public void setIsSearchHotItem(boolean b) {
        LogUtils.i("submitLog", "setIsSearchHotItem "+b);
        this.isSearchHotItem = b;
    }

    @Override
    protected void createView() {
        // TODO Auto-generated method stub
        int topMargin = SkyConstants.Div(30);
        iconImage = new CatchImageView(mContext);
        iconImage.setScaleType(ScaleType.CENTER_CROP);
        LayoutParams iconParams = new LayoutParams(iconWidth, iconWidth, Gravity.CENTER_VERTICAL);
        iconParams.leftMargin = SkyConstants.Div(25);
        this.addView(iconImage, iconParams);

        rightLayout = new LinearLayout(mContext);
        rightLayout.setOrientation(LinearLayout.VERTICAL);
        rightLayout.setGravity(Gravity.LEFT | Gravity.TOP);
        LayoutParams rightParams = new LayoutParams(LayoutParams.MATCH_PARENT, iconWidth);
        rightParams.setMargins(SkyConstants.Div(189), topMargin, SkyConstants.Div(20), 0);
        this.addView(rightLayout, rightParams);

        titleText = new AlwaysMarqueeTextView(mContext);
        titleText.setSelected(false);
        titleText.setTextSize(titleSize);
        SkinManager.setTextColor(titleText, R.color.titleColor);
        rightLayout.addView(titleText, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));

        infoText = UICommon.newTextView(mContext, infoTextSize, R.color.appInfoColor);
        infoText.setEllipsize(TruncateAt.END);
        rightLayout.addView(infoText, new LayoutParams(LayoutParams.MATCH_PARENT,
                LayoutParams.WRAP_CONTENT));
    }

    @Override
    public void update(SkyAppBaseData data) {
        // TODO Auto-generated method stub
        if (data == null)
            return;

        this.data = (SkyListAppData) data;
        pkgName = ((SkyListAppData) data).getPkgName();
        //特殊处理根据类名判断是否属于应用圈搜索
        LogUtils.i("pkgName: " + pkgName + ", is Game: " + data.isGame());
        if (!data.isGame()) {
            SkyAppDetailData.AppStatus status = SkyAppDetailData.AppStatus.NOT_DOWNLOADED;
            status = AppDataProvider.getInstance().isAppInstalled(pkgName);
            LogUtils.i("status: " + status);
            if (SkyAppDetailData.AppStatus.INSTALLED == status || SkyAppDetailData.AppStatus.INSTALLED_WITH_CAN_NOT_BE_UNINSTALLED == status) {
                addInstallTag();
            } else {
                removeInstallTag();
            }
        }

        if (data.getIconUrl() != null && !data.getIconUrl().equals("")) {
            if (SkyNetImageCache.getSkyNetImageCache().downloadAppListLogo(
                    ((SkyListAppData) data).getPkgName(), data.getIconUrl(), this, iconWidth, iconWidth, SkyConstants.Div(25))) {
                iconImage.setImageBitmap(null);
            } else {
                iconImage.setImageDrawable(SkinManager.getResDrawable(R.drawable.icon_default));
            }
        } else {
            try {
                iconImage.setImageDrawable(SkinManager.getResDrawable(R.drawable.icon_default));
                PackageInfo info = mContext.getPackageManager().getPackageInfo(
                        ((SkyListAppData) data).getPkgName(), 0);
                Drawable drawable = info.applicationInfo.loadIcon(mContext
                        .getPackageManager());
                try {
                    cornerBitmap = ImageUtils.getRoundedCornerBitmap(((BitmapDrawable) drawable).getBitmap(), SkyConstants.Div(25));
                    iconImage.setImageBitmap(cornerBitmap);
                } catch (Exception e) {
                    iconImage.setImageDrawable(drawable);
                }
            } catch (NameNotFoundException e) {
                e.printStackTrace();
            }
        }
        SpannableString s = new SpannableString(data.getTitle());
        HLPosition position = HLPositionUtil.getResult2(SearchController.mSearchKey.toLowerCase(),
                data.getTitle());
        CharacterStyle span = new ForegroundColorSpan(0xff88b8d9);
        LogUtils.d("search key is " + SearchController.mSearchKey + " and name is "
                + data.getTitle() + " position is " + position.start + " " + position.end);
        s.setSpan(span, position.start, position.end + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        titleText.setText(s);
        // UICommon.setText(titleText, data.getTitle());
        String showInfo = this.data.getShowInfo();
        UICommon.setText(infoText, showInfo, true);
        if (showInfo == null || showInfo.trim().length() == 0)
            rightLayout.setGravity(Gravity.LEFT | Gravity.CENTER_VERTICAL);

        String cornerUrl = this.data.getExtra();
        if (cornerUrl != null && cornerUrl.trim().length() > 0) {
            if (cornerImage == null) {
                cornerImage = new ImageView(mContext);
            }
            if (cornerImage.getParent() == null)
                this.addView(cornerImage, new LayoutParams(LayoutParams.WRAP_CONTENT,
                        LayoutParams.WRAP_CONTENT, Gravity.RIGHT | Gravity.TOP));
            cornerImage.setVisibility(View.INVISIBLE);
            SkyNetImageCache.getSkyNetImageCache().downloadUrl("", cornerUrl, this, iconWidth, iconWidth);
        }
    }

    public void updateShowInfo(String str) {
        UICommon.setText(infoText, str, true);
    }

    @Override
    protected void refreshImage(String url, Bitmap result) {
        // TODO Auto-generated method stub
        if (result == null)
            return;
        if (data != null && data.getIconUrl() != null && url.equals(data.getIconUrl())) {
            iconImage.setImageBitmap(result);
        } else if (data != null && data.getCornerIconUrl() != null
                && url.equals(data.getCornerIconUrl())) {
            if (cornerImage != null) {
                cornerImage.setImageBitmap(result);
                cornerImage.setVisibility(View.VISIBLE);
            }
        }
    }

    public String getDataId() {
        if (data == null)
            return null;
        return data.getId();
    }

    @Override
    public void onClick(View v) {
        if (data == null)
            return;
        LogUtils.d("detail", "onClick, data = " + data.toString());
        if (data.isGame()) {
            // Intent intent = new Intent("com.coocaa.gamecenter.detail");
            // intent.putExtra(DetailActivity.INTENT_APPID_KEY, data.getId());
            // intent.putExtra(DetailActivity.INTENT_PACKAGENAME_KEY, data.getPkgName());
            // mContext.startActivity(intent);

            LogUtils.d("id", data.getId());
            LogUtils.d("pkgname", data.getPkgName());
            Intent intent = new Intent("com.coocaa.gamecenter.detail");
            int appid = -1;
            try {
                appid = Integer.valueOf(data.getId());
            } catch (NumberFormatException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            intent.putExtra(DetailActivity.INTENT_APPID_KEY, appid);
            intent.putExtra(DetailActivity.INTENT_PACKAGENAME_KEY, data.getPkgName());
//            mContext.startActivity(intent);
            HashMap<String,String> map = new HashMap<String,String>();
            map.put("search_key",SearchController.mSearchKey);
            SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, false);
        } else {

            if(this.isSearchHotItem) {
                LogUtils.i("submitLog", "id = "+data.getId()
                        +", getPkgName = "+data.getPkgName()
                        +", title = "+data.getTitle());

                LogUtils.SubmitLog submitLog = new LogUtils.SubmitLog(LogUtils.PRODUCTID_APPSTORE,
                        "as2_search_recommend_onclick");
                submitLog.addParam("id", data.getId());
                submitLog.addParam("block_content_name", data.getTitle());
                submitLog.addParam("block_content_id", data.getPkgName());
                LogUtils.submit(submitLog);
            }

            Intent intent = new Intent(mContext, AppDetailActivity.class);
            intent.putExtra("id", this.data.getId());
            intent.putExtra("pkgName", "PPPPPPPPP");
//            mContext.startActivity(intent);
            HashMap<String,String> map = new HashMap<String,String>();
            map.put("search_key",SearchController.mSearchKey);
            SkyStartActivity.startActivity(mContext, mContext.getClass().getName(), intent, map, false);
        }
    }

    public void clearData() {
        this.data = null;
        iconImage.setImageBitmap(null);
        if (cornerBitmap != null && !cornerBitmap.isRecycled()) {
            cornerBitmap.recycle();
            cornerBitmap = null;
        }
        titleText.setText("");
        infoText.setText("");
        if (cornerImage != null)
            cornerImage.setVisibility(View.INVISIBLE);
    }

    public void setClickListener(OnItemClickListener listener) {
        this.clickListener = listener;
    }

}
